import path from 'node:path'
import process from 'node:process'

import { defineConfig, loadEnv } from 'vite'
import { createVitePlugins } from './vite/plugins'

// https://vitejs.dev/config/
export default async ({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_BASE, VITE_APP_API_PREFIX, VITE_APP_API_BASE_URL, VITE_DELETE_CONSOLE } = env
  console.table(env)

  return defineConfig({
    base: command === 'build' ? VITE_APP_BASE || '/' : '/',
    plugins: await createVitePlugins(env, command === 'build'),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: [
        { find: '~', replacement: path.resolve(__dirname, './') },
        { find: '@', replacement: path.resolve(__dirname, './src') },
      ],
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    // css: {
    //   preprocessorOptions: {
    //     scss: {
    //       api: 'modern-compiler',
    //       silenceDeprecations: ['legacy-js-api'],
    //     },
    //   },
    // },
    server: {
      hmr: true,
      host: '0.0.0.0',
      // open: false,
      proxy: {
        [VITE_APP_API_PREFIX]: {
          target: VITE_APP_API_BASE_URL,
          changeOrigin: true,
          secure: false,
          rewrite: p => p.replace(new RegExp(VITE_APP_API_PREFIX, 'g'), ''),
        },
      },
    },
    build: {
      // https://vite.dev/config/build-options.html
      sourcemap: command === 'build' ? false : 'inline',
      outDir: 'dist',
      assetsDir: 'static',
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
    },
    esbuild: {
      drop: command === 'build' && VITE_DELETE_CONSOLE === 'true' ? ['console', 'debugger'] : [],
    },
  })
}
